package cn.shadow.service;

import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

@Service
public class TimeService implements ITimeService {
    private final IThreadService threadService;
    private final AtomicLong currentMillSecond;
    private long lastResult;

    public TimeService(IThreadService threadService) {
        this.threadService = threadService;
        long ctime = System.currentTimeMillis();
        currentMillSecond = new AtomicLong(ctime);
        this.threadService.getScheduledExecutorService() //每一毫秒更新一次
                .scheduleAtFixedRate(this::setCurrentTime, 1, 1, TimeUnit.MILLISECONDS);
    }

    private void doSetCurrentTime(long ctime) {
        lastResult = ctime;
        currentMillSecond.lazySet(ctime);
    }

    private void setCurrentTime() {
        long ctime = System.currentTimeMillis() + getOffset();
        if (ctime <= lastResult) {
            // 每次返回的必须比上一次更大
            return;
        }
        doSetCurrentTime(ctime);
    }

    /**
     * 偏移量
     */
    private long getOffset() {
        return 0;
    }

    @Override
    public long getCurrentTime() {
        return currentMillSecond.get();
    }
}
